<?php
/**
 * Created by PhpStorm.
 * User: zoe
 * Date: 2018/7/18
 * Time: 下午4:56
 */
namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use Mrgoon\AliSms\AliSms;
use App\Http\Controllers\Constants;
use Illuminate\Support\Facades\Redis;
use Illuminate\Http\Request;

class SendMsgController extends Controller {
    private  $aliSms = null;

    public function __construct()
    {
        $this->aliSms = new AliSms();
    }

    public function sendVerificationCode(Request $request) {
        $data = $request->all();

        $templateCode = Constants::TEMPLATE_CODE;
        $phoneNumber = $data['phone_number'];
        $code = $this->setCode($phoneNumber);

        $data = array('code' => $code, 'product' => 'dsd');
        $response = $this->aliSms->sendSms($phoneNumber, $templateCode, $data);
        if($response->Code === 'OK'){
            $this->returnData(true, '发送成功', '');
        }else if($response->Code === 'isv.MOBILE_NUMBER_ILLEGAL'){
            $this->returnData(false, '请输入有效手机号', '');
        }else {
            $this->returnData(false, '验证失败', $response);
        }
    }

    private function setCode($phoneNumber){
        $code = rand(1000, 9999);
        $exists = Redis::keys("SMS{$phoneNumber}{$code}");
        if(empty($exists)){
            Redis::setex("SMS{$phoneNumber}{$code}", 300, $code);
        }

        return $code;
    }
}